package com.example.administrator.daydayappmarket.software.rating.fragment.hotrating.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.administrator.daydayappmarket.Contacts;
import com.example.administrator.daydayappmarket.R;
import com.example.administrator.daydayappmarket.software.choice.activity.SoftwareChoiceSecondActivity;
import com.example.administrator.daydayappmarket.software.choice.model.SoftwareChoiceTopicApps;
import com.example.administrator.daydayappmarket.software.rating.fragment.newrating.adapter.SoftwareRatingNewAdapter;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;

import com.example.administrator.daydayappmarket.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class RatingHotFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2{

    @InjectView(R.id.fragment_rating_new_listView)
    PullToRefreshListView listView;
    private SoftwareRatingNewAdapter adapter;//listView的适配器
    private List<SoftwareChoiceTopicApps> data;//总的数据源
    private List<SoftwareChoiceTopicApps> listData;//listView的数据源
    private RequestQueue requestQueue;//请求队列
    private int page=1;//刷新时的页数
    public static final String LISTVIEW="request";//listView网络请求时的标记

    public View headView;//头视图
    public List<SoftwareChoiceTopicApps> headData;//头视图的数据源

    //头视图的View
    private ImageView image1;
    private TextView nameText1;
    private TextView personText1;
    private ImageView image2;
    private TextView nameText2;
    private TextView personText2;
    private ImageView image3;
    private TextView nameText3;
    private TextView personText3;
    private RelativeLayout relativeLayout1;
    private RelativeLayout relativeLayout2;
    private RelativeLayout relativeLayout3;
    public RatingHotFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        data=new ArrayList<>();
        listData=new ArrayList<>();
        headData=new ArrayList<>();

        requestQueue = Volley.newRequestQueue(getContext());
        volleyData(null);


    }

    //请求数据
    private void volleyData(final PullToRefreshBase refreshView) {
        StringRequest request=new StringRequest(Request.Method.GET, Contacts.SOFTWARE_RATING_HOT + page, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                if (response != null) {
                    try {
                        JSONArray jsonArray=new JSONArray(response);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject=jsonArray.getJSONObject(i);
                            SoftwareChoiceTopicApps softwareChoiceTopicApps=new SoftwareChoiceTopicApps();
                            JSONObject jsonObject1=jsonObject.getJSONObject("data");
                            softwareChoiceTopicApps.parseJson(jsonObject1);
                            data.add(softwareChoiceTopicApps);
                            if(page<2){
                                if(i>2){
                                    listData.add(data.get(i));
                                }
                                if(i<3){
                                    headData.add(data.get(i));
                                }
                            }
                        }
                        if(page>1){
                            listData.addAll(data);
                        }


                        setHeadView(headView,headData);//设置头视图


                        adapter.notifyDataSetChanged();

                        if(refreshView!=null){
                            refreshView.onRefreshComplete();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                if(refreshView!=null){
                    refreshView.onRefreshComplete();
                }

            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> map=new HashMap<>();
                map.put(Contacts.HEADER_KEY,Contacts.HEADER_VALUES);

                return map;
            }
        };
        request.setTag(LISTVIEW);
        requestQueue.add(request);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_rating_new, container, false);
        ButterKnife.inject(this, view);

        adapter=new SoftwareRatingNewAdapter(getContext(),listData);
        listView.setAdapter(adapter);
        //设置刷新的模式
        listView.setMode(PullToRefreshBase.Mode.BOTH);
        listView.setOnRefreshListener(this);

        //设置空视图
        RelativeLayout relativeLayout= (RelativeLayout) view.findViewById(R.id.fragment_rating_new_emptyRelative);
        ImageView emptyImageVIew= (ImageView) view.findViewById(R.id.fragment_rating_new_emptyImageView);
        Glide.with(getContext()).load(R.drawable.cat_loading_transparent).into(emptyImageVIew);
        listView.setEmptyView(relativeLayout);

        //设置头视图
        headView=inflater.inflate(R.layout.fragment_software_rating_headview,null);
        listView.getRefreshableView().addHeaderView(headView);
        if(headData.size()!=0){
            setHeadView(headView,headData);
        }

        return view;
    }

    //设置头视图
    private void setHeadView(View headView, final List<SoftwareChoiceTopicApps> headData){
        if (headData != null) {
            initView(headView);
            Picasso.with(getContext()).load(headData.get(0).getIcon_url()).into(image1);
            nameText1.setText(headData.get(0).getName());
            personText1.setText(headData.get(0).getDownload_count()/10000 +" 万人下载");

            Picasso.with(getContext()).load(headData.get(1).getIcon_url()).into(image2);
            nameText2.setText(headData.get(1).getName());
            personText2.setText(headData.get(1).getDownload_count()/10000 +" 万人下载");

            Picasso.with(getContext()).load(headData.get(2).getIcon_url()).into(image3);
            nameText3.setText(headData.get(2).getName());
            personText3.setText(headData.get(2).getDownload_count()/10000 +" 万人下载");

            relativeLayout1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String id = headData.get(0).getId();
                    Intent intent=new Intent(getContext(),SoftwareChoiceSecondActivity.class);
                    intent.putExtra("id",id);
                    startActivity(intent);
                }
            });

            relativeLayout2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String id = headData.get(1).getId();
                    Intent intent=new Intent(getContext(),SoftwareChoiceSecondActivity.class);
                    intent.putExtra("id",id);
                    startActivity(intent);
                }
            });

            relativeLayout3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String id = headData.get(2).getId();
                    Intent intent=new Intent(getContext(),SoftwareChoiceSecondActivity.class);
                    intent.putExtra("id",id);
                    startActivity(intent);
                }
            });

        }
    }

    //初始化头视图中的控件
    private void initView(View headView) {
        image1= (ImageView) headView.findViewById(R.id.fragment_software_rating_head_firstImage);
        nameText1= (TextView) headView.findViewById(R.id.fragment_software_rating_head_firstNameText);
        personText1= (TextView) headView.findViewById(R.id.fragment_software_rating_head_firstPersonText);

        image2= (ImageView) headView.findViewById(R.id.fragment_software_rating_head_secondImage);
        nameText2= (TextView) headView.findViewById(R.id.fragment_software_rating_head_secondNameText);
        personText2= (TextView) headView.findViewById(R.id.fragment_software_rating_head_secondPersonText);

        image3= (ImageView) headView.findViewById(R.id.fragment_software_rating_head_thirdImage);
        nameText3= (TextView) headView.findViewById(R.id.fragment_software_rating_head_thirdNameText);
        personText3= (TextView) headView.findViewById(R.id.fragment_software_rating_head_thirdPersonText);

        relativeLayout1= (RelativeLayout) headView.findViewById(R.id.fragment_software_rating_head_relative1);
        relativeLayout2= (RelativeLayout) headView.findViewById(R.id.fragment_software_rating_head_relative2);
        relativeLayout3= (RelativeLayout) headView.findViewById(R.id.fragment_software_rating_head_relative3);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        requestQueue.cancelAll(LISTVIEW);
    }


    //下拉刷新
    @Override
    public void onPullDownToRefresh(final PullToRefreshBase refreshView) {
        page=1;
        listData.clear();
        data.clear();
        volleyData(refreshView);


    }

    //上拉刷新
    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        page++;
        data.clear();
        volleyData(refreshView);
    }

}
